package fr.enseirbmatmeca.apms.tapestry.pages;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.annotations.CleanupRender;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import fr.enseirbmatmeca.apms.spring.security.MyUserDetails;
import fr.enseirbmatmeca.apms.spring.security.ProjectRole;
import fr.enseirbmatmeca.apms.spring.service.ProjectManager;
import fr.enseirbmatmeca.apms.spring.service.UserManager;
import fr.enseirbmatmeca.apms.spring.service.impl.ProjectManagerImpl;

public class Security {
	// gère la securité, vérifie l'authentification et retourne le nom d'utilisateur, le role et la liste de projets

	@Inject
	protected Request request;
	
	@Inject
	protected UserManager userManager;
	
	@Inject
	protected ProjectManager projectManager;


	protected String errorMessage;
	
	protected MyUserDetails tapestryPrincipal;
	
	public String getRole(){
		// ROLE_ADMINISTRATOR or ROLE_USER
		if (getTapestryPrincipal()!=null)
			return ((GrantedAuthority) ((ArrayList)getTapestryPrincipal().getAuthorities()).get(0)).getAuthority();
		else 
			return null;
	} 

	public String getUsername(){
		// login
		if (getTapestryPrincipal()!=null)
			return getTapestryPrincipal().getUsername();
		else
			return null;
	} 
	
	public List<ProjectRole> getListProjectRole(String idProject){
		// list of project
		if (getTapestryPrincipal()!=null)
			return getTapestryPrincipal().getListProjectRole(idProject, userManager);
		else
			return null;
	}
	
	public MyUserDetails getTapestryPrincipal() {
		MyUserDetails tapestryPrincipal = null;
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

		if (authentication != null) {
			Object springSecurityPrincipal = authentication.getPrincipal();
			if (springSecurityPrincipal != null) {
				if (springSecurityPrincipal instanceof String) {
					tapestryPrincipal = null;
				} else {

					tapestryPrincipal = (MyUserDetails) springSecurityPrincipal;
				}
			}
		}
		return tapestryPrincipal;
	}

	public void onActivate(String loginError) {
		if("loginError=1".equals(loginError)) {
			this.errorMessage = "Error";
		}
	}
	
	@CleanupRender
	public void cleanup() {
		this.errorMessage = null;
	}
	
	public String getErrorMessage() {
		return this.errorMessage;
	}

}
